<?php
define('alzTreeMakerBotpath', str_replace("\\", "/", getcwd()) . '/');
define('alzTreeMaker_version', '0.5');
define('alzTreeMaker_date', '28. Oct. 2012');
define('alzTreeMaker_URL', '/plugins/AalzTreeMaker/main.php');
define('alzTreeMaker_Path', 'plugins/AalzTreeMaker/');
define('alzTreeMaker_settings', 'alzTreeMaker_settings.txt');
function AalzTreeMaker_init() {
	global $hooks;
	global $this_plugin;
	global $is_debug;
	global $mifilter;
	$hooks['after_load_settings'] = 'AalzTreeMaker_run';
	alzTreeMaker_createInfoTxt();
	echo "alzTreeMaker v" . alzTreeMaker_version . " by Team alz\r\n";
}
function AalzTreeMaker_run() {
	global $vWorldtype, $userId, $sequence_id;
	AddLog2('');
	list($userId, $flashRevision, $token, $sequence, $flashSessionKey, $xp, $energy) = explode(';', file_get_contents(F('params.txt')));
	$us = alzTreeMakerGetUs();
	if ($us['run'] === false) {
		AddLog2("alzTreeMaker v" . alzTreeMaker_version . " Nothing to do, bye.");
		return;
	}
	AddLog2("alzTreeMaker v" . alzTreeMaker_version . " Starting on $vWorldtype... ");
	$mainobjects = unserialize(file_get_contents(F('objects.txt')));
	$gb          = @unserialize(file_get_contents(F('ingiftbox.txt')));
	$mySection   = array(
		'bot_x' => 0,
		'bot_y' => 0,
		'top_x' => 100,
		'top_y' => 100
	);
	$cnt63       = 62999;
	$res         = 'OK';
	$rc          = 0;
	$ttree       = 0;
	$newRewards  = array();
	foreach ($us['item_array'] as $treename => $treecnt) {
		$mtree  = 0;
		$nwater = 1;
		while ($mtree < $treecnt) {
			if ($gb['wP'] > 0) {
				$gbitem = Units_GetUnitByCode('wP', true);
			} else {
				$res = 'No MysterySeedlings found in Giftbox, Plugin exiting now!';
				break;
			}
			if ($gb['wO'] < $nwater) {
				$res = "Not enough Water ($nwater needed) in Giftbox!";
				break;
			}
			
			if (0) DoInit(); # enable this to support trees with size bigger than 1x1!
			
			$tax = Parser_Find_Location($gbitem['code'], 'horizontal', $mySection);
			if ($tax === false) {
				$res = "No Space for placing Seedling ({$gb[$gbitem['code']]}) found!";
				break;
			}
			$gb[$gbitem['code']]--;
			$treeunit = Units_GetUnitByName($treename, true);
			$mtree++;
			$ttree++;
			AddLog2("alzTreeMaker: Place $ttree Seedling on Farm and grow to {$treeunit['realname']}...");
			$amf                           = new AMFObject("");
			$amf->_bodys[0]                = new MessageBody();
			$amf->_bodys[0]->targetURI     = 'FlashService.dispatchBatch';
			$amf->_bodys[0]->responseURI   = '/1/onStatus';
			$amf->_bodys[0]->responseIndex = '/1';
			$amf->_bodys[0]->_value[0]     = GetAMFHeaders();
			$cnt63++;
			$amfi                                                                      = 0;
			$amf->_bodys[0]->_value[1][$amfi]['sequence']                              = GetSequense();
			$amf->_bodys[0]->_value[1][$amfi]['sequenceID']                            = $sequence_id;
			$amf->_bodys[0]->_value[1][$amfi]['functionName']                          = 'WorldService.performAction';
			$amf->_bodys[0]->_value[1][$amfi]['params']                                = array();
			$amf->_bodys[0]->_value[1][$amfi]['params'][0]                             = 'place';
			$amf->_bodys[0]->_value[1][$amfi]['params'][1]['itemName']                 = $gbitem['name'];
			$amf->_bodys[0]->_value[1][$amfi]['params'][1]['className']                = $gbitem['className'];
			$amf->_bodys[0]->_value[1][$amfi]['params'][1]['id']                       = $cnt63;
			$amf->_bodys[0]->_value[1][$amfi]['params'][1]['direction']                = 0;
			$amf->_bodys[0]->_value[1][$amfi]['params'][1]['plantTime']                = time();
			$amf->_bodys[0]->_value[1][$amfi]['params'][1]['position']                 = array();
			$amf->_bodys[0]->_value[1][$amfi]['params'][1]['position']['x']            = $tax['x'];
			$amf->_bodys[0]->_value[1][$amfi]['params'][1]['position']['y']            = $tax['y'];
			$amf->_bodys[0]->_value[1][$amfi]['params'][1]['position']['z']            = 0;
			$amf->_bodys[0]->_value[1][$amfi]['params'][1]['contents'][0]['numItem']   = 7;
			$amf->_bodys[0]->_value[1][$amfi]['params'][1]['contents'][0]['itemCode']  = 'wO';
			$amf->_bodys[0]->_value[1][$amfi]['params'][1]['isFullyBuilt']             = 0;
			$amf->_bodys[0]->_value[1][$amfi]['params'][1]['seedType']                 = $treeunit['code'];
			$amf->_bodys[0]->_value[1][$amfi]['params'][2]                             = array();
			$amf->_bodys[0]->_value[1][$amfi]['params'][2][0]['isGift']                = true;
			$amf->_bodys[0]->_value[1][$amfi]['params'][2][0]['isInventoryWithdrawal'] = false;
			$amf->_bodys[0]->_value[1][$amfi]['params'][2][0]['isStorageWithdrawal']   = -1;
			$amf->_bodys[0]->_value[1][$amfi]['params'][2][0]['giftMetadataIndex']     = -1;
			$amf->_bodys[0]->_value[1][$amfi]['params'][2][0]['expansionLevel']        = 0;
			$amf->_bodys[0]->_value[1][$amfi]['params'][2][0]['metadata']              = NULL;
			$amf->_bodys[0]->_value[1][$amfi]['params'][2][0]['currency']              = '';
			$amf->_bodys[0]->_value[2]                                                 = 0;
			$sbc                                                                       = 0;
			$res                                                                       = '';
			while ($sbc < 10 && $res != 'OK') {
				$amf2 = RequestAMFIntern($amf, true);
				$res  = CheckAMF2Response($amf2);
				if ($res != 'OK')
					GetSequenseback();
				$sbc++;
			}
			if ($res != 'OK')
				break;
			if ($us['selltrees'] === false) {
				Parser_Occupy_Location($tax, $gbitem['code']);
			}
			AddLog2("alzTreeMaker: water " . $gbitem['realname'] . " on Farm => $res");
			$sid                                                                  = $amf2->_bodys[0]->_value['data'][0]['data']['id'];
			$treeids[]                                                            = $sid;
			$amf                                                                  = new AMFObject("");
			$amf->_bodys[0]                                                       = new MessageBody();
			$amf->_bodys[0]->targetURI                                            = 'FlashService.dispatchBatch';
			$amf->_bodys[0]->responseURI                                          = '/1/onStatus';
			$amf->_bodys[0]->responseIndex                                        = '/1';
			$amf->_bodys[0]->_value[0]                                            = GetAMFHeaders();
			$amfi                                                                 = 0;
			$amf->_bodys[0]->_value[1][$amfi]['sequence']                         = GetSequense();
			$amf->_bodys[0]->_value[1][$amfi]['sequenceID']                       = $sequence_id;
			$amf->_bodys[0]->_value[1][$amfi]['functionName']                     = 'WorldService.performAction';
			$amf->_bodys[0]->_value[1][$amfi]['params']                           = array();
			$amf->_bodys[0]->_value[1][$amfi]['params'][0]                        = 'store';
			$amf->_bodys[0]->_value[1][$amfi]['params'][1]['tempId']              = -1;
			$amf->_bodys[0]->_value[1][$amfi]['params'][1]['direction']           = 0;
			$amf->_bodys[0]->_value[1][$amfi]['params'][1]['className']           = $gbitem['className'];
			$amf->_bodys[0]->_value[1][$amfi]['params'][1]['state']               = 'construction';
			$amf->_bodys[0]->_value[1][$amfi]['params'][1]['itemName']            = $gbitem['name'];
			$amf->_bodys[0]->_value[1][$amfi]['params'][1]['id']                  = $sid;
			$amf->_bodys[0]->_value[1][$amfi]['params'][1]['position']            = array();
			$amf->_bodys[0]->_value[1][$amfi]['params'][1]['position']['x']       = $tax['x'];
			$amf->_bodys[0]->_value[1][$amfi]['params'][1]['position']['y']       = $tax['y'];
			$amf->_bodys[0]->_value[1][$amfi]['params'][1]['position']['z']       = 0;
			$amf->_bodys[0]->_value[1][$amfi]['params'][2]                        = array();
			$amf->_bodys[0]->_value[1][$amfi]['params'][2][0]['isFull']           = 1;
			$amf->_bodys[0]->_value[1][$amfi]['params'][2][0]['storedClassName']  = 'BuildingPart';
			$amf->_bodys[0]->_value[1][$amfi]['params'][2][0]['currency']         = '';
			$amf->_bodys[0]->_value[1][$amfi]['params'][2][0]['resource']         = 0;
			$amf->_bodys[0]->_value[1][$amfi]['params'][2][0]['cameFromLocation'] = 0;
			$amf->_bodys[0]->_value[1][$amfi]['params'][2][0]['storedItemCode']   = 'wO';
			$amf->_bodys[0]->_value[1][$amfi]['params'][2][0]['isGift']           = true;
			$amf->_bodys[0]->_value[2]                                            = 0;
			$amf2                                                                 = RequestAMFIntern($amf, true);
			$res                                                                  = CheckAMF2Response($amf2);
			if ($res !== 'OK')
				break;
			$gb['wO']--;
			$growtree = 'none';
			for ($amfi = 0; $amfi < 1; $amfi++) {
				if (isset($amf2->_bodys[0]->_value['data'][$amfi]['data']['rewardLink']) && isset($amf2->_bodys[0]->_value['data'][$amfi]['data']['finishedName'])) {
					$newRewards[$rc]['type']       = 'xxxtree';
					$newRewards[$rc]['rewardLink'] = $amf2->_bodys[0]->_value['data'][$amfi]['data']['rewardLink'];
					$newRewards[$rc]['timestamp']  = time();
					$growtree                      = $amf2->_bodys[0]->_value['data'][$amfi]['data']['finishedName'];
					$newRewards[$rc]['rewardItem'] = Units_GetRealnameByName($growtree);
					AddLog2("alzTreeMaker: Water @last -> add " . ($rc + 1) . ". RewardLink to MyRewardsList => " . $newRewards[$rc]['rewardItem']);
					$rc++;
				} else {
					AddLog2("alzTreeMaker: Error Getting RewardLink.");
				}
			}
			if ($us['selltrees'] === true && $growtree != 'none') {
				$amf                                                        = new AMFObject("");
				$amf->_bodys[0]                                             = new MessageBody();
				$amf->_bodys[0]->targetURI                                  = 'FlashService.dispatchBatch';
				$amf->_bodys[0]->responseURI                                = '/1/onStatus';
				$amf->_bodys[0]->responseIndex                              = '/1';
				$amf->_bodys[0]->_value[0]                                  = GetAMFHeaders();
				$amfi                                                       = 0;
				$amf->_bodys[0]->_value[1][$amfi]['sequence']               = GetSequense();
				$amf->_bodys[0]->_value[1][$amfi]['sequenceID']             = $sequence_id;
				$amf->_bodys[0]->_value[1][$amfi]['functionName']           = 'WorldService.performAction';
				$amf->_bodys[0]->_value[1][$amfi]['params']                 = array();
				$amf->_bodys[0]->_value[1][$amfi]['params'][0]              = 'sell';
				$amf->_bodys[0]->_value[1][$amfi]['params'][1]['tempId']    = -1;
				$amf->_bodys[0]->_value[1][$amfi]['params'][1]['direction'] = 0;
				$amf->_bodys[0]->_value[1][$amfi]['params'][1]['className'] = 'Tree';
				$amf->_bodys[0]->_value[1][$amfi]['params'][1]['state']     = 'bare';
				$amf->_bodys[0]->_value[1][$amfi]['params'][1]['itemName']  = $growtree;
				$amf->_bodys[0]->_value[1][$amfi]['params'][1]['id']        = $sid;
				$amf->_bodys[0]->_value[1][$amfi]['params'][1]['position']      = array();
				$amf->_bodys[0]->_value[1][$amfi]['params'][1]['position']['x'] = $tax['x'];
				$amf->_bodys[0]->_value[1][$amfi]['params'][1]['position']['y'] = $tax['y'];
				$amf->_bodys[0]->_value[1][$amfi]['params'][1]['position']['z'] = 0;
				$amf->_bodys[0]->_value[1][$amfi]['params'][2]                  = array();
				$amf->_bodys[0]->_value[2]                                      = 0;
				$amf2                                                           = RequestAMFIntern($amf);
				$res                                                            = CheckAMF2Response($amf2);
				AddLog2("alzTreeMaker: Sell Tree " . $newRewards[$rc - 1]['rewardItem'] . " -> $res");
			}
		}
		if ($res !== 'OK')
			break;
	}
	if (count($newRewards) > 0) {
		AddLog2("alzTreeMaker: Writing Rewards in Myrewards-Table...");
		$vRewardsArrayNew = array();
		$vRewardsArrayOld = unserialize(file_get_contents(F('rewards.txt')));
		if (count($vRewardsArrayOld) > 0) {
			foreach ($vRewardsArrayOld as $vRewardTmp) {
				$vRewardsArrayNew[] = $vRewardTmp;
			}
		}
		foreach ($newRewards as $key => $vRewardTmp) {
			$vRewardsArrayNew[] = $vRewardTmp;
		}
		save_botarray($vRewardsArrayNew, F('rewards.txt'));
	}
	if ($res != 'OK') {
		AddLog2("alzTreeMaker: Aborting run, Error: $res");
	}
	if ($us['disable'] || $res != 'OK')
		$us['run'] = false;
	save_array($us, alzTreeMaker_settings);
	AddLog2("alzTreeMaker: All done, bye");
	if ($ttree > 0)
		doInit();
}
function alzTreeMakerGetUs($vFile = '') {

	if ($vFile != '') {
		$us = @unserialize(file_get_contents($vFile));
	} else {
		$us = load_array(alzTreeMaker_settings);
	}
	$us['run']          = isset($us['run']) ? $us['run'] : false;
	$us['disable']      = isset($us['disable']) ? $us['disable'] : false;
	$us['onlynomaster'] = isset($us['onlynomaster']) ? $us['onlynomaster'] : true;
	$us['onlylvl1']     = isset($us['onlylvl1']) ? $us['onlylvl1'] : true;
	$us['selltrees']    = isset($us['selltrees']) ? $us['selltrees'] : false;
	$us['item_array']   = isset($us['item_array']) ? $us['item_array'] : array();
	return $us;
}
function AalzTreeMaker_form() {
	global $vParserImagePath, $vWorldtype;
	global $vUnlockedWorldtypes;
	list($userId, $flashRevision, $token, $sequence, $flashSessionKey, $xp, $energy, $flashrev) = explode(';', file_get_contents(F('params.txt')));
	$mifilter = strtoupper($_GET['mifilter']);
	$setFarm  = $_GET['get_farm'];
	if (empty($setFarm))
		$setFarm = $vWorldtype;
	$fullsettingname = alzTreeMaker_Path . Parser_WorldPrefix($setFarm) . $userId . '_' . alzTreeMaker_settings;
	$tmp_path        = getcwd();
	$img_path        = str_replace("/", "\\", $tmp_path);
	$img_url         = "file:///" . $img_path . "/";
	$vWorldtypesik   = $vWorldtype;
	$vWorldtype      = $setFarm;
	echo '<html><head><style type="text/css"> body {background-color:silver;} </style></head><body>';
	Parser_HTML_StatusBar();
	echo '<h3><font color="darkred">al</font><font color="blue">z</font>TreeMaker v' . alzTreeMaker_version . ' [ ' . alzTreeMaker_date . ' ] Make Trees from Seedlings by <font color="darkred">al</font>s & rs<font color="blue">z</font>!</h3>';
	$vWorldtype  = $vWorldtypesik;
	$mainobjects = unserialize(file_get_contents("FBID_" . Parser_WorldPrefix($setFarm) . $userId . '/objects.txt'));
	$gb          = @unserialize(file_get_contents(F('ingiftbox.txt')));
	if (isset($_GET['deletelist']) && $_GET['delrewardsok']) {
		$vRewardsArray = unserialize(file_get_contents(F('rewards.txt')));
		foreach ($vRewardsArray as $vReward) {
			if ($vReward['type'] == 'xxxtree')
				continue;
			$vRewardsArrayNew[] = $vReward;
		}
		save_botarray($vRewardsArrayNew, F('rewards.txt'));
	}
	if (isset($_GET['showlist'])) {
		$vRewardsArray = unserialize(file_get_contents(F('rewards.txt')));
		foreach ($vRewardsArray as $vReward) {
			if ($vReward['type'] != 'xxxtree')
				continue;
			if ($vReward['timestamp'] < (time() - (60 * 60 * 24)))
				continue;
			$vTmpArray[$vReward['rewardItem']][] = 'http://apps.facebook.com/onthefarm/' . str_replace('&key={*key*}', '', $vReward['rewardLink']);
		}
		$vFileName = "plugins\\AalzTreeMaker\\rewards_$userId.txt";
		if (is_file($vFileName))
			unlink($vFileName);
		$vFile = fopen($vFileName, "w+");
		fwrite($vFile, "from http://www.facebook.com/profile.php?id=$userId \r\n");
		fwrite($vFile, " \r\n");
		foreach ($vTmpArray as $vRewName => $vRewards) {
			fwrite($vFile, count($vRewards) . " $vRewName:\r\n");
			$vCnt = 1;
			$rr   = 1;
			foreach ($vRewards as $vReward) {
				fwrite($vFile, $rr++ . '. ' . $vRewName . ': ' . $vReward . "\r\n");
			}
			fwrite($vFile, "\r\n");
		}
		fclose($vFile);
		$vVMD     = "notepad.exe $vFileName";
		$WshShell = new COM("WScript.Shell");
		$WshShell->Run($vVMD, 5, false);
	}
	$issaved = false;
	if (isset($_POST['submit']) || isset($_POST['clear'])) {
		$ns                 = array();
		$ns['run']          = isset($_POST['run']) ? true : false;
		$ns['disable']      = isset($_POST['disable']) ? true : false;
		$ns['onlynomaster'] = isset($_POST['onlynomaster']) ? true : false;
		$ns['onlylvl1']     = isset($_POST['onlylvl1']) ? true : false;
		$ns['selltrees']    = isset($_POST['selltrees']) ? true : false;
		if (!isset($_POST['clear'])) {
			if (isset($_POST['items2'])) {
				$ns['item_array'] = array();
				$tmp_list         = (array) ($_POST['items2']);
				foreach ($tmp_list as $tmp_item) {
					if (isset($_POST[$tmp_item])) {
						$item_details                = Units_GetUnitByName((string) $tmp_item);
						$tmp_num                     = (integer) $_POST[$tmp_item];
						$ns['item_array'][$tmp_item] = $tmp_num;
					}
				}
			}
		}
		if (count($ns['item_array']) > 0)
			$issaved = true;
		file_put_contents($fullsettingname, serialize($ns));
	}
	$us = alzTreeMakerGetUs($fullsettingname);
	echo '<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>';

	echo '<form action="' . alzTreeMaker_URL . '" method="post">';
	echo '<table border="0" cellpadding="5"><tr><td>';
	echo '<tr><td>';
	echo str_repeat('&nbsp;', 2) . 'Load Farm: <select size="1" name="get_farm">';
	foreach ($vUnlockedWorldtypes as $vUWt) {
		echo '<option value="' . $vUWt . '"';
		if ($setFarm == $vUWt)
			echo 'selected';
		echo '>' . $vUWt . '</option>';
	}
	echo '</select>';
	echo str_repeat("&nbsp;", 5) . '<input type="submit" name="loadsettings" value="Load Settings">';
	echo '</td><td>';
	echo '</td>';
	echo '</tr><tr><td>';
	echo '<input type="checkbox" name="run" value="true"' . ($us['run'] ? ' checked > ' : ' > ');
	echo '<b>Run alzTreeMaker?</b>';
	echo '<br>' . str_repeat("&nbsp;", 6) . '<input type="checkbox" name="disable" value="true"' . ($us['disable'] ? ' checked > ' : ' > ');
	echo ' Disable plugin after running?';
	echo '<td>';
	echo str_repeat("&nbsp;", 6) . '<input type="submit" name="showlist" value="Show RewardLinks">';
	echo '</td>';
	echo '</tr><tr><td>';
	echo str_repeat("&nbsp;", 6) . '<input type="checkbox" name="onlynomaster" value="true"' . ($us['onlynomaster'] ? ' checked > ' : ' > ');
	echo ' Show only unmastered Trees?';
	echo '</td>';
	echo '<td><input type="checkbox" name="delrewardsok" value="true"> ' . '<input type="submit" name="deletelist" value="Delete RewardLinks">';
	if (isset($_POST['deletelist']) && $_POST['delrewardsok'])
		echo '<i>deleted!</i>';
	echo '<br>' . str_repeat("&nbsp;", 6) . '<font color="purple" size="2">only Rewards from Treemaker!</font></td>';
	echo '</tr><tr><td>';
	echo str_repeat("&nbsp;", 6) . '<input type="checkbox" name="onlylvl1" value="true"' . ($us['onlylvl1'] ? ' checked > ' : ' > ');
	echo ' Show only Level 1 Trees?';
	echo '</td>';
	echo '</tr><tr><td>';
	echo str_repeat("&nbsp;", 6) . '<input type="checkbox" name="selltrees" value="true"' . ($us['selltrees'] ? ' checked > ' : ' > ');
	echo ' Delete Trees on Farm after watering?';
	echo '</td>';
	echo '</tr>';
	echo '<tr><td>';
	if (!isset($gb['7mp']))
		$gb['7mp'] = 0;
	if (!isset($gb['wP']))
		$gb['wP'] = 0;
	echo str_repeat("&nbsp;", 11) . '<font color="purple">' . $gb['wP'] . ' Mystery Seedling and ' . $gb['wO'] . ' Water in Giftbox</font>';
	echo '</td></tr>';
	echo '</table>';
	echo '<br>' . str_repeat("&nbsp;", 10) . '<input type="submit" name="submit" value="Save Settings">';
	if (isset($_POST['submit']))
		echo '&nbsp;<i>OK!</i>';
	echo '&nbsp;&nbsp;<input type="submit" name="clear" value="Clear All Selections">';
	if (isset($_POST['clear']))
		echo '&nbsp;<i>OK!</i>';
	echo '&nbsp;&nbsp;<input type="submit" name="refre" value="show all">';
	echo '&nbsp;&nbsp;search: <input type="text" name="mifilter" size="15" value="' . $mifilter . '">';
	echo '&nbsp;&nbsp;<input type="submit" name="fifind" value="Find">';
	echo '<hr>';
?>
<script>
var world = '<?=$vWorldtype?>';
var worldre = new RegExp(world,'i');
function updateSel() {
	var num = 0;
	$('table#treemakertable td.treepic input[type=text]').each(function (i,e) {
		num += parseInt($(e).val()) || 0;
	});
	
	$('span#totalNum').html(num);
}
function removeNonZero() {
	$('table#treemakertable td.treepic').each(function(i,e){
		var html=$(e).html();
		var ma = new Array();
		if ( ma=html.match( /\([1-9]\d*\// )) {
			$(e).next().addBack().hide();
		}
	});
	updateSel();
}
function removeUnmasterable() {
	$('table#treemakertable td.treepic').each(function(i,e){
		var html=$(e).html();
		if (! html.match( /\(/ )) {
			$(e).next().addBack().hide();
		}
	});
	updateSel();
}
function removeForeignWorlds(onlyme) {
	$('table#treemakertable td.treename').each(function(i,e){
		var html=$(e).html();
		var ma = new Array();
		var mw = new RegExp('world: '+world,'i');
		if (onlyme && ! html.match(mw)) {
			$(e).prev().addBack().hide();
			return;
		}
		if (ma=html.match( /world:\s*\w+/i )) {
			 if (! ma[0].match(worldre)) {
				$(e).prev().addBack().hide();
			 }
		}
	});
	updateSel();
}
function removeBroken() {
	$('table#treemakertable td.treename').each(function(i,e){
		var html=$(e).html();
		if (html.match(/\[91[bfk]\]/)) {
			$(e).prev().addBack().hide();
		}
	});
	updateSel();
}
function plusone() {
	$('table#treemakertable td.treepic:visible').each(function(i,e){
		var old = 0;
		if (parseInt($(e).find('input[type=text]').val()) > 0) {
			old = parseInt($(e).find('input[type=text]').val());
		}
		$(e).find('input[type=text]').val(old + 1);
		$(e).find('input[type=checkbox]').attr('checked',true);
	});
	updateSel();
}
$(function() {
	updateSel();
});

</script>
<span id="totalNum">0</span> trees selected.<br>
<button type="button" onclick="removeUnmasterable();return false;">Hide un-masterables</button>
<button type="button" onclick="removeBroken();return false;">Hide broken</button>
<button type="button" onclick="removeNonZero();return false;">Hide non-zero harvests</button>
<button type="button" onclick="removeForeignWorlds(false);return false;">Hide foreign worlds</button>
<button type="button" onclick="removeForeignWorlds(true);return false;">show only <?=$vWorldtype?></button>
<button type="button" onclick="plusone();return false;">+1 for all</button>
<button type="button" onclick="$('table#treemakertable td').show();return false;">Show all</button>

<?php	

	$alltrees     = Units_GetBy("field='type' and content='tree'", true);
	$allnextlevel = array();
	foreach ($alltrees as $key => $opt) {
		if (isset($opt['nextLevel'])) {
			$allnextlevel[$opt['nextLevel']] = $opt['nextLevel'];
		}
	}
	if (file_exists('FBID_' . $userId . '/AllMyItems.txt')) {
		$recitems = unserialize(file_get_contents('FBID_' . $userId . '/AllMyItems.txt'));
	}
	$vHarvestCounts = load_botarray(F('cropmastery.txt'));
	$vMasteryLevels = load_botarray(F('cropmasterycount.txt'));
	if (count($alltrees) > 0 && $gb['wP'] > 0) {
		echo '<table border="1" rules="rows" id="treemakertable" cellpadding="2" >';
		$tmp_array = $us["item_array"];
		$sp        = 0;
		
		foreach ($alltrees as $key => $opt) {
			if ($opt['code'] == 'XX')
				continue;
			if ($opt['code'] == 'y*')
				continue;
			if ($us['onlylvl1'] && in_array($opt['code'], $allnextlevel))
				continue;
			if (strlen($mifilter) > 0) {
				if (strpos(strtoupper($opt['name']), $mifilter) === false && strpos(strtoupper($opt['realname']), $mifilter) === false)
					continue;
			}
			
			$starttime = 0;
			if (isset($opt['limitedStart'])) {
				$starttime = strtotime($opt['limitedStart']);
			}
			if (time() < $starttime)
				continue;
			if ($us['onlynomaster']) {
				if (isset($vMasteryLevels[$opt['code']])) {
					if ($vMasteryLevels[$opt['code']] >= 2)
						continue;
				}
			}
			$endtime = 0;
			if (isset($opt['limitedEnd'])) {
				$endtime = strtotime($opt['limitedEnd']);
			}
			if ($issaved) {
				if (!isset($us["item_array"][$key]))
					continue;
				if ($us["item_array"][$key] <= 0)
					continue;
			}
			if ($sp % 2) {
				// echo '<td width="10"></td>';
			} else {
				echo '<tr>';
			}
			echo "<td align=\"center\" class=\"treepic\" treename=\"{$opt["name"]}\" harvests=\""
			.$vHarvestCounts[Units_GetCodeByName($opt['name'])]."\">";
			if (file_exists($img_url . $opt["iconurl"])) {
				echo '<img src="' . $img_url . $opt["iconurl"] . '" width="70"/>';
			} else {
				echo '<img src="' . $opt["iconurlremote"] . '" width="70"/>';
			}
			echo '<br> <font color="purple" size="2">';
			echo alzGetMasteryByName($vHarvestCounts, $vMasteryLevels, $opt["name"], true);
			echo "<br> ";
			echo '<input type="checkbox" name="items2" value="' . $key . '"';
			if (array_key_exists($key, $us["item_array"]))
				echo ' checked="yes">';
			echo '</input>';
			echo '<input type="text" name="' . $key . '" size="1" value="' . $us["item_array"][$key] . '"></input>';
			echo '</td>';
			echo "<td class=\"treename\" treename=\"{$opt["name"]}\">";
			echo '<b><font face="Tahoma" color="blue" size="2">' . $opt["realname"] . '</font></b>';
			echo '<br><font face="Tahoma" color="blue" size="2">' . $opt["name"] . ' [' . $opt["code"] . ']</font></b>';
			if (in_array($opt['code'], $allnextlevel)) {
				echo '<br><font face="Tahoma" color="blue" size="3">Level 2</font></b>';
			} else {
				echo '<br><b><font face="Tahoma" color="green" size="3">Level 1</font></b>';
			}
			if (isset($opt["limitedStart"]))
				echo '<br><b><font face="Tahoma" color="darkred" size="2"> Start: ' . (string) $opt["limitedStart"] . '</font></b>';
			if (isset($opt["limitedEnd"]))
				echo '<br><b><font face="Tahoma" color="darkred" size="2"> Ended: ' . (string) $opt["limitedEnd"] . '</font></b>';
			if (isset($opt["marketCardDescriptor"]))
				echo '<br><font face="Tahoma" color="blue" size="2">MarketInfo:' . $opt["marketCardDescriptor"] . '</font>';
			if (isset($opt["requirement_0_className"]))
				echo '<br><b><font face="Tahoma" color="blue" size="2"> ' . $opt["requirement_0_className"] . ': ' . $opt["requirement_0_name"] . '</font></b>';
			if (isset($opt["requirement_1_className"]))
				echo '<br><b><font face="Tahoma" color="blue" size="2"> ' . $opt["requirement_1_className"] . ': ' . $opt["requirement_1_name"] . '</font></b>';
			if (isset($opt["requirement_2_className"]))
				echo '<br><b><font face="Tahoma" color="blue" size="2"> ' . $opt["requirement_2_className"] . ': ' . $opt["requirement_2_name"] . '</font></b>';
			if (isset($opt["requirement_3_className"]))
				echo '<br><b><font face="Tahoma" color="blue" size="2"> ' . $opt["requirement_3_className"] . ': ' . $opt["requirement_3_name"] . '</font></b>';
			if (isset($opt["requirement_4_className"]))
				echo '<br><b><font face="Tahoma" color="blue" size="2"> ' . $opt["requirement_4_className"] . ': ' . $opt["requirement_4_name"] . '</font></b>';
			if (isset($opt["experimentGate"]))
				echo '<br><font face="Tahoma" color="blue" size="2"> experimentGate: ' . $opt["experimentGate"] . '</font></b>';
			if (isset($opt["requiredLevel"]))
				echo '<br><font face="Tahoma" color="blue" size="2"> required Level: ' . $opt["requiredLevel"] . '</font></b>';
			if (isset($recitems[$opt["code"]]['total'])) {
				echo '<br><font face="Tahoma" color="purple" size="2">';
				echo $recitems[$opt["code"]]['total'] . 'x found in your Inventory!</font>';
				echo '</font>';
			}
			echo '</td>';
			if ($sp % 2)
				echo '</tr>';
			$sp++;
		}
		if (!($sp % 2))
			echo '</tr>';
		echo '</table></td></tr>';
	} else {
		echo "<br> ";
		echo "<br> ";
		echo '<br><font color="darkred" size="4"> NO MysterySeedlings found!</font>';
	}
	echo '</form>';
}
function alzGetMasteryByName($vHarvestCounts, $vMasteryLevels, $vName, $vStars = false) {
	return (alzGetMasteryByCode($vHarvestCounts, $vMasteryLevels, Units_GetCodeByName($vName), $vStars));
}
function alzGetMasteryByCode($vHarvestCounts, $vMasteryLevels, $vCode, $vStars = false) {
	$vHarvestCount = @$vHarvestCounts[$vCode];
	$vMasteryLevel = @$vMasteryLevels[$vCode];
	if (strlen($vHarvestCount) == 0)
		$vHarvestCount = 0;
	if (strlen($vMasteryLevel) == 0) {
		$vMasteryLevel = 0;
	} else {
		$vMasteryLevel++;
	}
	$vUnit = Units_GetUnitByCode($vCode);
	if ($vUnit['masterymax'] < 1) {
		$vMasteryLevel = '-1';
	}
	if (strlen($vMasteryLevel) == 0)
		$vMasteryLevel = 0;
	if ($vStars) {
		if ($vMasteryLevel == '-1')
			return '';
		if ($vMasteryLevel == '0')
			return ' - (' . $vHarvestCount . "/{$vUnit['masterymax']})";
		if ($vMasteryLevel == '1')
			return ' * (' . $vHarvestCount . "/{$vUnit['masterymax']})";
		if ($vMasteryLevel == '2')
			return ' ** (' . $vHarvestCount . "/{$vUnit['masterymax']})";
		if ($vMasteryLevel == '3')
			return ' *** (' . $vHarvestCount . "/{$vUnit['masterymax']})";
	}
	return $vMasteryLevel;
}
function alzTreeMaker_createInfoTxt() {
	$save_str = "alzTreeMaker by alz\r\n";
	$save_str .= alzTreeMaker_version . " - " . alzTreeMaker_date . "\r\n";
	$f = fopen(alzTreeMaker_Path . 'info.txt', "w+");
	fputs($f, $save_str, strlen($save_str));
	fclose($f);
}
?>